'use strict';

const qiniu = require('qiniu');
const Service = require('egg').Service;
const { Op } = require('sequelize');

class UserImageService extends Service {

    async findByUserId(userId) {
        return await this.ctx.model.UserImage.findAll({
            where: {
                user_id: userId,
                online: true
            },
            order: [
                ['index', 'ASC']
            ]
        })
    }

    // 七牛云token
    async getToken() {
        const bucket = this.config.qiniu.bucket;

        // 鉴权
        const mac = new qiniu.auth.digest.Mac(this.config.qiniu.AK, this.config.qiniu.SK);
        const options = {
            expires: 7200 * 4,
            scope: bucket // 你的七牛存储对象
        };
        const putPolicy = new qiniu.rs.PutPolicy(options);
        const uploadToken = putPolicy.uploadToken(mac);
        return uploadToken;
    }

    // 上传七牛云链接
    async addUserImage(params) {
        
        const { ctx } = this;

        // 查询数据是否存在
        const currentImage = await ctx.model.UserImage.findOne({
            where: {
                user_id: params.user_id,
                index: params.index
            }
        });
        if (currentImage) {  // 更新照片
            return await ctx.model.UserImage.update({image: params.image}, {
                where: {
                    user_id: params.user_id,
                    index: params.index
                }
            });
        }
        
        // 新增
        return await ctx.model.UserImage.create(params);
        
    }
}

module.exports = UserImageService;